<?php

namespace Upfor\UpforPHP\Library;

use Monolog\Logger as MonoLogger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;

/**
 * 日志工具类
 */
class ErrorLogger {

    protected static $logger;

    /**
     * Get logger instance
     *
     * @return MonoLogger
     */
    public static function getInstance() {
        if (!self::$logger) {
            // The default date format is "Y-m-d H:i:s"
            $dateFormat = "Y-m-d H:i:s";
            // The default output format is "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
            $output = "[%datetime%] %level_name%: %message% %context%\n";
            // Create a formatter
            $formatter = new LineFormatter($output, $dateFormat);

            // Create a handler
            $stream = new StreamHandler(config('log')['error'], MonoLogger::DEBUG);
            $stream->setFormatter($formatter);

            // Bind it to a logger object
            self::$logger = new MonoLogger('TaskRunner');
            self::$logger->pushHandler($stream);
        }

        return self::$logger;
    }

    /**
     * Add a error log
     *
     * @param string       $level DEBUG|INFO|NOTICE|WARNING|ERROR|CRITICAL|ALERT|EMERGENCY
     * @param string|array $message
     * @param array        $context
     */
    public static function log($level, $message, array $context = array()) {
        self::getInstance()->log($level, $message, $context);
    }

}
